const { citys } = require('../../utils/city.js'); 
Page({
  data: {
    statusBarHeight: 0, // 状态栏高度
    detail: '', // 门牌号
    label: '', // 标签
    consignee: '', // 联系人
    sex: '', // 性别
    phone: '', // 手机号
    labelOptions: ['家', '公司', '学校', '父母家'], // 标签选项
    sexOptions: ['男', '女'], // 性别选项
    isDefault: false, // 是否设置为默认地址
    regionData: [],          // 原始数据
    provinces: [],           // 省份列表
    cities: [],              // 城市列表
    counties: [],            // 区县列表
    provinceIndex: 0,        // 当前选中省份索引
    cityIndex: 0,            // 当前选中城市索引
    countyIndex: 0,          // 当前选中区县索引
    selectedProvince: '',    // 选中省份名称
    selectedCity: '',        // 选中城市名称
    selectedCounty: ''       // 选中区县名称
  },
  
  // 返回按钮点击事件
  onBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },

  onLoad: function (options) {
    const windowInfo = wx.getWindowInfo();
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight,
      regionData: citys || [],
      provinces: citys.map(p => p.name) // 初始化省份（字符串数组）

    });
  },

  // 省份选择变化
  onProvinceChange(e) {
    const index = e.detail.value;
    const selectedProvince = this.data.regionData[index];
    const cities = selectedProvince.city.map(c => c.name);
    const selectedCity = this.data.regionData[index].city[this.data.cityIndex];
    const counties = selectedCity.area;
    const selectedCounty = counties[this.data.countyIndex];
    this.setData({
      provinceIndex: index,
      cities: cities,
      counties: selectedProvince.city[0]?.area || [],
      selectedProvince: selectedProvince.name,
      selectedCity: selectedCity.name,
      selectedCounty: selectedCounty,
      cityIndex: 0,
      countyIndex: 0
    });
  },

  // 城市选择变化
  onCityChange(e) {
    const index = e.detail.value;
    const selectedCity = this.data.regionData[this.data.provinceIndex].city[index];
    const counties = selectedCity.area;
    const selectedCounty = counties[this.data.countyIndex];
    this.setData({
      cityIndex: index,
      counties: counties,
      selectedCity: selectedCity.name,
      selectedCounty: selectedCounty,
      countyIndex: 0
    });
  },

  // 区县选择变化
  onCountyChange(e) {
    const index = e.detail.value;
    this.setData({
      countyIndex: index,
      selectedCounty: this.data.counties[index] || ''
    });
  },
  // 输入框事件
  onInputDoorNumber: function (e) {
    this.setData({ detail: e.detail.value });
  },
  onInputConsignee: function (e) {
    this.setData({ consignee: e.detail.value });
  },
  onInputPhone: function (e) {
    this.setData({ phone: e.detail.value });
  },

  // 选择器事件
  onChangeLabel: function (e) {
    this.setData({ label: this.data.labelOptions[e.detail.value] });
  },
  onChangeSex: function (e) {
    this.setData({ sex: this.data.sexOptions[e.detail.value] });
  },

  onChangeDefault: function (e) {
    this.setData({
      isDefault: e.detail.value
    });
  },

  onSaveAddress: function () {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    const address = {
      userId: app.globalData.userInfo.id,
      consignee: this.data.consignee,
      sex: this.data.sex,
      phone: this.data.phone,
      provinceName: this.data.selectedProvince,
      cityName: this.data.selectedCity,
      districtName: this.data.selectedCounty,
      detail: this.data.detail,
      label: this.data.label,
      isDefault: this.data.isDefault ? 1 : 0 // 默认地址
    };
  
    // 如果设置为默认地址，先调用接口将所有地址设置为非默认
    if (this.data.isDefault) {
      wx.request({
        url: `http://localhost:8080/manage/address/clearDefault/${address.userId}`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            // clearDefault 成功后，再保存地址
            this.saveAddress(address);
          } else {
            wx.showToast({
              title: '清除默认地址失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }
      });
    } else {
      // 如果不是默认地址，直接保存
      this.saveAddress(address);
    }
  },
  
  // 保存地址的公共方法
  saveAddress: function (address) {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    wx.request({
      url: 'http://localhost:8080/manage/address',
      method: 'POST',
      data: address,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '地址保存成功',
            icon: 'success'
          });
          // 获取父页面实例并手动刷新数据
          const pages = getCurrentPages();
          if (pages.length > 1) {
            const parentPage = pages[pages.length - 2];
            parentPage.getAddressList();
          }
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        } else {
          wx.showToast({
            title: '保存失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  }
});